package com.h4313.ghome;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;
import com.h4313.ghome.io.ServerUtilities;
import com.h4313.ghome.ui.HomeActivity;

public class GCMIntentService extends GCMBaseIntentService {

	@Override
	protected void onError(Context arg0, String arg1) {
	}

	@Override
	protected void onMessage(Context context, Intent intent) {

		
		Log.i(TAG, "Received message");
		String message = "pouet";

		String type = intent.getStringExtra("temp");
		String payload = intent.getStringExtra("payload");
		
		if (type != null && payload != null) {
			generateNotification(context, message);
		} else {
			generateNotification(context, payload);
		}
		
	}

	@Override
	protected void onRegistered(Context ctx, String regId) {

		Log.i(TAG, "Device registered: regId = " + regId);
		ServerUtilities.register(ctx, regId);

	}

	@Override
	protected void onUnregistered(Context arg0, String arg1) {
	}

	private static void generateNotification(Context context, String message) {
		int icon = R.drawable.ic_stat_gcm;
		long when = System.currentTimeMillis();

		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);

		// Notification notification = new Notification(icon, message, when);
		//
		// String title = context.getString(R.string.app_name);
		Intent notificationIntent = new Intent(context, HomeActivity.class);
		// set intent so it does not start a new activity
		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_SINGLE_TOP);

		PendingIntent intent = PendingIntent.getActivity(context, 0,
				notificationIntent, 0);
		// notification.setLatestEventInfo(context, title, message, intent);
		// notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.;
		
		Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

		Notification notification = new Notification.Builder(context)
				.setWhen(when).setContentTitle(message).setSmallIcon(icon)
				.setContentIntent(intent).setAutoCancel(true)
				.setSound(uri)
				.getNotification();

		notificationManager.notify(0, notification);
	}
}
